
package com.kugou.game.sdk.ui.fragment;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.adapter.RechargeMoneyGridAdapter;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.BasePayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeIndexMode;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.interfaces.OnSmsPayListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;
import com.vsofo.vsofopay.IPayResultCallback;
import com.vsofo.vsofopay.SDKAPI;

/**
 * 描述:短信支付
 *
 * @author wcj
 * @since 2015年11月18日 下午3:41:03
 */
public class RechargeBySMSFragment extends BaseRechargeFragment {

    private static final int MSG_REQUEST_PAY_INFO = 1;

    private static final int MSG_REQUEST_PAY_INFO_SUCCESS = 2;

    private static final int MSG_REQUEST_PAY_INFO_FAILED = 3;

    private static int[] moneys = {
            2, 5, 10, 15, 20, 30
    };

    private Context mContext;

    private GridView mGridView;

    private RechargeMoneyGridAdapter mAdapter;

    private int mRechargeValue;

    private String mOrderId;

    public static RechargeBySMSFragment getInstance(boolean rechargeYoubi) {
        RechargeBySMSFragment fragment = new RechargeBySMSFragment();
        fragment.mIsRechargeYoubi = rechargeYoubi;
        return fragment;
    }

    private RechargeBySMSFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int viewId = Rx.layout.kg_fragment_recharge_by_sms;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            viewId = Rx.layout.kg_fragment_recharge_by_sms_land;
        }

        return inflater.inflate(viewId, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        initView();
        updateCanGotKubi();
    }

    private void initView() {

        Button submitBtn = (Button) findViewById(Rx.id.kg_btn_summit);
        submitBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                sendEmptyBackgroundMessage(MSG_REQUEST_PAY_INFO);
                // 发送统计--点击确认支付按钮
                sendClickConfirmRechargeBtnStatics(ChargeType.TYPE_SMS, mRechargeValue);
            }
        });

        TextView selectNumTitle = (TextView) findViewById(Rx.id.kg_choose_charge_num_title);
        selectNumTitle.setText("请选择充值金额（运营商需收取" + PayManager.getSmsPercent() + "%渠道费用）");

        TextView rechargeDesc = (TextView) findViewById(Rx.id.kg_sms_recharge_desc);
        rechargeDesc.setText("● 运营商需收取" + PayManager.getSmsPercent() + "%渠道费用（即充值20元，实际到账"
                + (int) (20.0 * PayManager.getSmsPercent() / 100) + "元）");

        mGridView = (GridView) findViewById(Rx.id.kg_gridview);
        mAdapter = new RechargeMoneyGridAdapter(mContext, moneys, RechargeMoneyGridAdapter.UNIT_YUN);
        mGridView.setAdapter(mAdapter);

        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            mGridView.setNumColumns(6);
        }

        // 恢复上次支付金额
        mAdapter.setmMoneyIndex(0);
        mRechargeValue = moneys[0];

        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter.getItem(position) == 0) {
                    return;
                }

                if (!NetWorkUtil.isNetworkAvailable(mContext)) {
                    showToast("请检查您的网络连接");
                    return;
                }

                mAdapter.onItemClick(parent, view, position, id);
                mAdapter.notifyDataSetChanged();
                mRechargeValue = (Integer) mAdapter.getItem(position);

                updateCanGotKubi();
            }
        });
    }

    private void updateCanGotKubi() {
        if (mIsRechargeYoubi) {
            updateCanGotKubiTextView(mRechargeValue, ChargeType.TYPE_SMS);
        }
    }

    private void payBySms(String orderId, String url, String param, String desc) {
        String spurl = url + "?" + param;
        SDKAPI.startPay(getActivity(), spurl, desc, payResultCallback);
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }
        switch (msg.what) {
            case MSG_REQUEST_PAY_INFO_SUCCESS:
                hideLoadingView();
                payBySms(msg.getData().getString("orderId"), msg.getData().getString("url"), msg
                        .getData().getString("param"), msg.getData().getString("desc"));
                break;

            case MSG_REQUEST_PAY_INFO_FAILED:
                hideLoadingView();
                showToast(msg.obj.toString());
                break;
            default:
                break;
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);

        switch (msg.what) {
            case MSG_REQUEST_PAY_INFO:
                showLoadingView();
                requestPayInfo();

                break;

            default:
                break;
        }
    }

    private void requestPayInfo() {
        BasePayRequestParams requestParams = new BasePayRequestParams();
        mOrderId = SDKControler.createNewOrderId();
        if (mIsRechargeYoubi) {
            // 生成唯一字符串
            mOrderId = UUID.randomUUID().toString();
            requestParams.setDirectCharge(0);
        } else {
            requestParams.setDirectCharge(1);
        }

        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_SMS);
        requestParams.setMoney(mRechargeValue * 100);
        requestParams.setOutOrderId(mOrderId);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        PayManager.payBySMS(requestParams, new OnSmsPayListener() {

            @Override
            public void onSuccess(String orderId, String url, String param, String desc) {
                Message msg = new Message();
                msg.what = MSG_REQUEST_PAY_INFO_SUCCESS;
                Bundle data = new Bundle();
                data.putString("orderId", orderId);
                data.putString("url", url);
                data.putString("param", param);
                data.putString("desc", desc);
                msg.setData(data);
                sendUiMessage(msg);

            }

            @Override
            public void onFailed(String errorMsg) {
                Message msg = new Message();
                msg.what = MSG_REQUEST_PAY_INFO_FAILED;
                msg.obj = errorMsg;
                sendUiMessageDelayed(msg, 1000);

            }
        });
    }

    // SDK回调函数
    private IPayResultCallback payResultCallback = new IPayResultCallback() {
        @Override
        public void onPayResult(int resultCode, String description, String orderNumber) {
            onResult(resultCode, description, orderNumber);
        }
    };

    public void onResult(int resultCode, String description, String orderNumber) {
        // 状态码
        // 100 提示内容：支付请求已提交，请返回账户查询。
        // 101 失败提示内容：根据SDK返回文本提示。
        // 102手动操作提示内容：请到收件箱接收短信，并根据短信回复确认内容完成支付。
        // 109提示内容：用户退出支付。（未支付就退出）
        LogUtil.d("onResult", "状态码：" + resultCode);
        LogUtil.d("onResult", "数据说明：" + description);
        LogUtil.d("onResult", "订单号：" + orderNumber);
        String errorStr = "";
        int recordtype = 0;

        if (100 == resultCode) {
            // 充值成功
            if (getOnEventListener() != null) {
                getOnEventListener().onRechargeSuccess(ChargeIndexMode.MODE_SMS, mRechargeValue);
                sendRechargeSuccessEvent(mOrderId, ChargeType.TYPE_SMS, mRechargeValue);
            }
            return;
        } else if (102 == resultCode) {
            errorStr = "请到收件箱查收短信，并根据短信回复确认内容完成支付";
        } else if (109 == resultCode) {
            errorStr = "用户退出支付";
        } else {
            int errorCode = getErrorCode(description);
            if (errorCode == 110) {
                errorStr = "暂不支持该面值充值，请更换其他面值";
            } else if (errorCode == 140 || errorCode == 190 || errorCode == 200) {
                errorStr = "您的手机号暂不支持，请更换其他手机号码";
            } else {
                errorStr = description;
            }
        }

        showNoticeDialog(errorStr);
        sendCancelRechargeStatics(ChargeType.TYPE_SMS, mRechargeValue, mOrderId, recordtype,
                errorStr);
        ;
    }

    public static int getErrorCode(String description) {
        try {
            String regex = "\\d+";
            Pattern pt = Pattern.compile(regex);
            Matcher mc = pt.matcher(description);
            if (mc.find()) {
                return Integer.parseInt(mc.group(0));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 显示一些消息提示的确定弹框
     * 
     * @param tips 弹框Message
     */
    private void showNoticeDialog(String tips) {
        if (isDetached()) {
            return;
        }
        final BaseConfirmDialog failedDialog = new BaseConfirmDialog(getActivity());
        failedDialog
                .setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        failedDialog.setMessage(TextUtils.isEmpty(tips) ? "" : tips);
        failedDialog.setCancelBtnVisibility(View.GONE);
        failedDialog.setContentGravity(Gravity.CENTER);
        failedDialog.setOKBtnText("知道了");
        failedDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                failedDialog.dismiss();

            }
        });
        failedDialog.show();
    }
}
